from app import db
from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)

    @property
    def password(self):
        raise AttributeError("password is not a readable attribute")

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    email = db.Column(db.String(64), unique=True)
    role_id = db.Column(db.Integer, db.ForeignKey('Role.id'))

    def __repr__(self):
        return f"{self.id}-{self.username}"

    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'password': self.verify_password,
            'email': self.email,
            'role_id': self.role_id
        }


class Role(db.Model):
    __tablename__ = "roles"
    id = db.Column(db.Integer, primary_key=True)
    rolename = db.Column(db.String(16), unique=True)
    users = db.relationship('User', backref='role', lazy='dynamic')
    limits = db.relationship("Limit", secondary="Role2Limit", backref="roles")

    def __repr__(self):
        return f"{self.id}-{self.rolename}"


class Limit(db.Model):
    __tablename__ = "limits"
    id = db.Column(db.Integer, primary_key=True)
    limitname = db.Column(db.Integer, unique=True)

    def __repr__(self):
        return f"{self.id}-{self.limitname}"


db.Table(
    "Role2Limit",
    db.Column('id', db.Integer, primary_key=True),
    db.Column('role_id', db.Integer, db.ForeignKey('Role.id')),
    db.Column('limit_id', db.Integer, db.ForeignKey('Limit.id'))
)
